package com.twetec.cms.adapter.pc.backend.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twetec.cms.adapter.pc.backend.response.R;
import com.twetec.cms.adapter.pc.backend.response.ResultCodeMsgEnum;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.system.SystemApiWhiteListPO;
import com.twetec.cms.model.po.user.UserPO;
import com.twetec.cms.model.po.website.ArticleModelPO;
import com.twetec.cms.model.vo.system.WhitListPageListVO;
import com.twetec.cms.model.vo.system.WhiteListGetOneVO;
import com.twetec.cms.model.vo.system.WhiteListVO;
import com.twetec.cms.model.vo.website.ArticleModelPageListVO;
import com.twetec.cms.model.vo.website.ArticleModelVO;
import com.twetec.cms.service.system.SystemApiWhiteListService;
import com.twetec.cms.service.ucenter.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "白名单管理")
@CrossOrigin
@RestController
@RequestMapping("/system/whit-list")
public class WhitListController {

    @Autowired
    UserService userService;

    @Autowired
    private SystemApiWhiteListService systemApiWhiteListService;

    @ApiOperation(value = "新增白名单", notes = "新增白名单")
    @PostMapping("/create")
    public R create(
            @ApiParam(value = "名称", required = true, example = "某某白名单") @RequestParam(required = false) String name,
            @ApiParam(value = "keyId", required = true, example = "XXXXXX") @RequestParam(required = false) String keyId,
            @ApiParam(value = "KeySecret", required = true, example = "adsfasdfasdf") @RequestParam(required = false) String keySecret,
            @ApiParam(value = "IP地址,多个使用英文逗号分隔", required = true, example = "10.23.222.147,10.23.222.148") @RequestParam(required = false) String ipAddrList,
            @ApiParam(value = "备注", required = false, example = "备注信息") @RequestParam(required = false) String remark,
            @RequestAttribute("userId") Long userId) {

        // 参数校验
        if (StringUtils.isBlank(name)) { return R.failureRequestParam().msg("名称必填"); }
        if (StringUtils.isBlank(keyId)) { return R.failureRequestParam().msg("keyId必填"); }
        if (StringUtils.isBlank(keySecret)) { return R.failureRequestParam().msg("keySecret必填"); }
        if (StringUtils.isBlank(ipAddrList)) { return R.failureRequestParam().msg("IP地址必填"); }

        boolean result = systemApiWhiteListService.create(name, keyId, keySecret, ipAddrList, remark, 0, userId);
        return result ? R.success() : R.failure();
    }

    @ApiOperation(value = "根据id更新", notes = "根据id更新")
    @PutMapping("/update-by-id")
    public R updateById(
            @ApiParam(value = "id", required = true, example = "1") @RequestParam(required = false) Long id,
            @ApiParam(value = "名称", required = true, example = "白名单") @RequestParam(required = false) String name,
            @ApiParam(value = "keyId", required = true, example = "XXXXXX") @RequestParam(required = false) String keyId,
            @ApiParam(value = "keySecret", required = true, example = "asdasdasdad") @RequestParam(required = false) String keySecret,
            @ApiParam(value = "iP地址", required = true, example = "10.23.222.147") @RequestParam(required = false) String ipAddrList,
            @ApiParam(value = "备注", required = false, example = "备注信息") @RequestParam(required = false) String remark,
            @RequestAttribute("userId") Long userId) {

        // 参数校验
        if (id == null || StringUtils.isBlank(String.valueOf(id))) { return R.failureRequestParam().msg("id必填"); }
        if (StringUtils.isBlank(keyId)) { return R.failureRequestParam().msg("kId必填"); }
        if (StringUtils.isBlank(keySecret)) { return R.failureRequestParam().msg("keySecret必填"); }
        if (StringUtils.isBlank(ipAddrList)) { return R.failureRequestParam().msg("IP地址必填"); }

        boolean result = systemApiWhiteListService.updateById(id, name, keyId, keySecret, ipAddrList, remark, userId);

        return result ? R.success() : R.failure();
    }

    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    @DeleteMapping("/delete-by-id")
    public R deleteById(
            @ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id) {
        // 参数校验
        if (id == null || StringUtils.isBlank(String.valueOf(id))) { return R.failureRequestParam().msg("id必填"); }

        boolean result = systemApiWhiteListService.removeById(id);

        return result? R.success() : R.serviceError();
    }

    @ApiOperation(value = "根据id更新状态", notes = "根据id更新状态")
    @PutMapping("/update-status-by-id")
    public R updateStatusById(
            @ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id,
            @ApiParam(value = "状态(1:启用 0禁用)", required = true, example = "1") @RequestParam(required = false) Integer status,
            @RequestAttribute("userId") Long userId) {

        // 参数校验
        if (id == null || StringUtils.isBlank(String.valueOf(id))) { return R.failureRequestParam().msg("id必填"); }
        if (status == null) { return R.failureRequestParam().msg("status必填"); }

        boolean result = systemApiWhiteListService.updateStatusById(id, status, userId);

        return result ? R.success() : R.serviceError();
    }

    @ApiOperation(value = "根据id获取", notes = "根据id获取")
    @GetMapping("/get-by-id")
    public R<WhiteListGetOneVO> getById(
            @ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id) {

        // 参数校验
        if (id == null || StringUtils.isBlank(String.valueOf(id))) { return R.failureRequestParam().msg("id必填"); }

        WhiteListGetOneVO whiteListGetOneVO = systemApiWhiteListService.getById(id);
        if (null == whiteListGetOneVO) {
            return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);
        }

        return R.success().data(whiteListGetOneVO);
    }

    @ApiOperation(value = "分页搜索列表", notes = "分页搜索列表")
    @GetMapping("/page-search-list")
    public R<WhiteListVO> pageSearchList(
            @ApiParam(value = "名字", required = false, example = "XXXX白名单") @RequestParam(required = false) String name,
            @ApiParam(value = "keyId", required = false, example = "xxxxxxx") @RequestParam(required = false) String keyId,
            @ApiParam(value = "keySecret", required = false, example = "xxxxxxx") @RequestParam(required = false) String keySecret,
            @ApiParam(value = "备注", required = false, example = "xxx") @RequestParam(required = false) String remark,
            @ApiParam(value = "状态", required = false, example = "0") @RequestParam(required = false) Integer status,
            @ApiParam(value = "IP地址", required = false, example = "10.23.222.147") @RequestParam(required = false) String ipAddrList,
            @ApiParam(value = "更新人", required = false, example = "张三") @RequestParam(required = false) String modifierName,
            @ApiParam(value = "根据更新时间搜索的开始时间（10位时间戳）", required = false, example = "1234567891") @RequestParam(required = false) Date gmtModifiedStart,
            @ApiParam(value = "根据更新时间搜索的结束时间（10位时间戳）", required = false, example = "1231231231") @RequestParam(required = false) Date gmtModifiedEnd,
            @ApiParam(value = "要访问的页码", required = true, example = "1") @RequestParam(required = false) Integer page,
            @ApiParam(value = "页面容量", required = true, example = "10") @RequestParam(required = false) Integer limit,
            @RequestAttribute("userId") Long userId) {

        // TODO:: 打包时userId要注释
//        Long userId = 1371387567439171585L;

        // 校验访问页码
        if (page == null || StringUtils.isBlank(String.valueOf(page))) { return R.failureRequestParam().msg("访问页码必填"); }
        if (!ValidateUtil.Number(String.valueOf(page))) { return R.failureRequestParam().msg("访问页码格式有误"); }
        // 校验访问数据条数
        if (limit == null || StringUtils.isBlank(String.valueOf(limit))) { return R.failureRequestParam().msg("访问数据条数必填"); }
        if (!ValidateUtil.Number(String.valueOf(limit))) { return R.failureRequestParam().msg("访问数据条数格式有误"); }

        // 返回给前端的数据
        WhitListPageListVO whitListPageListVO = new WhitListPageListVO();

        // 搜索条件
        QueryWrapper<SystemApiWhiteListPO> systemApiWhiteListPOQueryWrapper = new QueryWrapper<>();

        // 添加模型名称
        if (StringUtils.isNotEmpty(name)) systemApiWhiteListPOQueryWrapper.like("NAME", name);
        if (StringUtils.isNotEmpty(keyId)) systemApiWhiteListPOQueryWrapper.like("KEY_ID", keyId);
        if (StringUtils.isNotEmpty(keySecret)) systemApiWhiteListPOQueryWrapper.like("KEY_SECRET", keySecret);
        if (StringUtils.isNotEmpty(remark)) systemApiWhiteListPOQueryWrapper.like("REMARK", remark);
        if (status != null) systemApiWhiteListPOQueryWrapper.eq("status", status);
        if (StringUtils.isNotEmpty(ipAddrList)) systemApiWhiteListPOQueryWrapper.like("IP_ADDR_LIST", ipAddrList);

        // 根据更新人name查询更新人id
        List<UserPO> userPOList = null;
        if (StringUtils.isNotEmpty(modifierName)) {
            QueryWrapper<UserPO> userWrapper = new QueryWrapper<>();
            userWrapper.like("NAME", modifierName);
            userPOList = userService.list(userWrapper);
        }
        // 更新人ID
        if (userPOList != null && userPOList.size() > 0) {
            ArrayList<Long> userIdList = new ArrayList<>();
            for (UserPO userPO : userPOList) {
                userIdList.add(userPO.getId());
            }
            systemApiWhiteListPOQueryWrapper.in("MODIFIER_ID", userIdList);
        }

        // 当更新人id查询结果为空，但是传入的更新人姓名不为空的时候，表示表中没有对应的操作人，直接返回空集合
        if ((userPOList == null || userPOList.size() == 0) && StringUtils.isNotEmpty(modifierName)) {
            whitListPageListVO.setPage(page);
            whitListPageListVO.setLimit(limit);
            whitListPageListVO.setTotal(0);
            whitListPageListVO.setList(new ArrayList<>());
            return R.success().data(whitListPageListVO);
        }

        // 添加更新时间
        if (gmtModifiedStart != null) systemApiWhiteListPOQueryWrapper.ge("GMT_MODIFIED", gmtModifiedStart);
        if (gmtModifiedEnd != null) systemApiWhiteListPOQueryWrapper.le("GMT_MODIFIED", gmtModifiedEnd);
        // 根据更新时间倒序排列
        systemApiWhiteListPOQueryWrapper.orderByDesc("GMT_MODIFIED");

        // 开始分页查询
        Page<SystemApiWhiteListPO> systemApiWhiteListPOPage = systemApiWhiteListService.page(new Page<>(page, limit), systemApiWhiteListPOQueryWrapper);


        // VO数据
        whitListPageListVO.setTotal((int)systemApiWhiteListPOPage.getTotal());
        whitListPageListVO.setLimit((int)systemApiWhiteListPOPage.getSize());
        whitListPageListVO.setPage((int)systemApiWhiteListPOPage.getCurrent());

        List<SystemApiWhiteListPO> records = systemApiWhiteListPOPage.getRecords();
        ArrayList<WhiteListVO> whiteListVOArrayList = new ArrayList<>();

        // 只有查询到了数据才转换
        if (records != null && records.size() > 0) {
            for (SystemApiWhiteListPO record : records) {
                WhiteListVO whiteListVO = new WhiteListVO();
                BeanUtils.copyProperties(record, whiteListVO);
                // 更新人姓名
                UserPO userPO = userService.getById(record.getModifierId());
                if (userPO != null) whiteListVO.setModifierName(userPO.getName());
                whiteListVOArrayList.add(whiteListVO);
            }
        }

        whitListPageListVO.setList(whiteListVOArrayList);

        return R.success().data(whitListPageListVO);
    }
}
